<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="产品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in productCategory"
            :key="item.value"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
         <el-select v-model="queryParams.status" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in statusOptions"
           :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品规格" prop="standard">
        <el-input
          v-model="queryParams.standard"
          placeholder="请输入产品规格"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="产品备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入产品备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="保质期天数" prop="expiryDay">
        <el-input
          v-model="queryParams.expiryDay"
          placeholder="请输入保质期天数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="采购价格" prop="purchasePrice">
        <el-input
          v-model="queryParams.purchasePrice"
          placeholder="请输入采购价格，单位：元"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品属性" prop="productAttribute">
        <el-input
          v-model="queryParams.productAttribute"
          placeholder="请输入产品属性"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="批号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="货号" prop="itemNo">
        <el-input
          v-model="queryParams.itemNo"
          placeholder="请输入货号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="重量" prop="weightNew">
        <el-input
          v-model="queryParams.weightNew"
          placeholder="请输入重量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="尺码" prop="size">
        <el-input
          v-model="queryParams.size"
          placeholder="请输入尺码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单重" prop="singleWeight">
        <el-input
          v-model="queryParams.singleWeight"
          placeholder="请输入单重"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input
          v-model="queryParams.contractNumber"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-row :gutter="10" style="margin-bottom: 16px">
      <el-col :span="12" />
      <el-col :span="12">
        <div style="text-align: right">
          <el-button type="default" plain @click="btnLie">
            <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
            列表字段
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="产品编号" v-if="visibleColumns.id" align="center" prop="id" width="140" />
      <el-table-column label="产品名称" v-if="visibleColumns.name" align="center" prop="name" />
      <el-table-column
        label="产品条码"
        v-if="visibleColumns.barCCode"
        align="center"
        prop="barCCode"
      />
      <el-table-column
        label="产品分类"
        v-if="visibleColumns.categoryId"
        align="center"
        prop="categoryId"
      />
      <el-table-column label="单位编号" v-if="visibleColumns.unitId" align="center" prop="unitId" />
      <el-table-column label="产品状态" v-if="visibleColumns.status" align="center" prop="status" />
      <el-table-column
        label="产品规格"
        v-if="visibleColumns.standard"
        align="center"
        prop="standard"
      />
      <el-table-column label="产品备注" v-if="visibleColumns.remark" align="center" prop="remark" />
      <el-table-column
        label="保质期天数"
        v-if="visibleColumns.expiryDay"
        align="center"
        prop="expiryDay"
      />
      <el-table-column
        label="基础重量（kg）"
        v-if="visibleColumns.weight"
        align="center"
        prop="weight"
      />
      <el-table-column
        label="采购价格，单位：元"
        v-if="visibleColumns.purchasePrice"
        align="center"
        prop="purchasePrice"
      />
      <el-table-column
        label="销售价格，单位：元"
        v-if="visibleColumns.salePrice"
        align="center"
        prop="salePrice"
      />
      <el-table-column
        label="最低价格，单位：元"
        v-if="visibleColumns.minPrice"
        align="center"
        prop="minPrice"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        v-if="visibleColumns.createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        v-if="visibleColumns.warehouseLocationId"
        label="库位"
        align="center"
        prop="warehouseLocationId"
      />
      <el-table-column
        v-if="visibleColumns.warehouseAreaId"
        label="仓库区域"
        align="center"
        prop="warehouseAreaId"
      />
      <el-table-column
        v-if="visibleColumns.productAttribute"
        label="产品属性"
        align="center"
        prop="productAttribute"
      />
      <el-table-column
        v-if="visibleColumns.unit"
        label="单位（基本单位）"
        align="center"
        prop="unit"
        width="180px"
      />
      <el-table-column
        v-if="visibleColumns.warehousingRemark"
        label="入库备注"
        align="center"
        prop="warehousingRemark"
      />
      <el-table-column
        v-if="visibleColumns.secondaryUnit"
        label="副单位"
        align="center"
        prop="secondaryUnit"
      />
      <el-table-column
        v-if="visibleColumns.secondaryUnitQuantity"
        label="副单位数量"
        align="center"
        prop="secondaryUnitQuantity"
      />
      <el-table-column
        v-if="visibleColumns.salePriceSecondary"
        label="销售单价（辅助单位）"
        align="center"
        prop="salePriceSecondary"
        width="180px"
      />
      <el-table-column
        v-if="visibleColumns.costPriceSecondary"
        label="成本单价（辅助单位）"
        align="center"
        prop="costPriceSecondary"
        width="180px"
      />
      <el-table-column
        v-if="visibleColumns.batchNumber"
        label="批号"
        align="center"
        prop="batchNumber"
      />
      <el-table-column
        v-if="visibleColumns.supplierName"
        label="供应商名称"
        align="center"
        prop="supplierName"
      />
      <el-table-column v-if="visibleColumns.spec" label="规格" align="center" prop="spec" />
      <el-table-column
        v-if="visibleColumns.outerBoxSize"
        label="外箱尺寸"
        align="center"
        prop="outerBoxSize"
      />
      <el-table-column
        v-if="visibleColumns.customerName"
        label="客户名称"
        align="center"
        prop="customerName"
      />
      <el-table-column v-if="visibleColumns.itemNo" label="货号" align="center" prop="itemNo" />
      <el-table-column
        v-if="visibleColumns.packageInfo"
        label="包装"
        align="center"
        prop="packageInfo"
      />
      <el-table-column
        v-if="visibleColumns.cuttingCostPerMeter"
        label="切割费用/米"
        align="center"
        prop="cuttingCostPerMeter"
      />
      <el-table-column
        v-if="visibleColumns.piercingCostPerPiece"
        label="刺穿点费用/个"
        align="center"
        prop="piercingCostPerPiece"
      />
      <el-table-column
        v-if="visibleColumns.dottingCostPerPiece"
        label="打点费用/个"
        align="center"
        prop="dottingCostPerPiece"
      />
      <el-table-column
        v-if="visibleColumns.weightNew"
        label="重量"
        align="center"
        prop="weightNew"
      />
      <el-table-column v-if="visibleColumns.size" label="尺码" align="center" prop="size" />
      <el-table-column
        v-if="visibleColumns.singleWeight"
        label="单重"
        align="center"
        prop="singleWeight"
      />
      <el-table-column v-if="visibleColumns.length" label="长" align="center" prop="length" />
      <el-table-column v-if="visibleColumns.width" label="宽" align="center" prop="width" />
      <el-table-column v-if="visibleColumns.height" label="高" align="center" prop="height" />
      <el-table-column v-if="visibleColumns.density" label="密度" align="center" prop="density" />
      <el-table-column
        v-if="visibleColumns.contractNumber"
        label="合同编号"
        align="center"
        prop="contractNumber"
      />
      <el-table-column label="操作" align="center" fixed="right" width="160px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:product:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 自定义字段 -->
  <el-dialog v-model="dialogVisible" title="自定义字段" width="50%" :before-close="handleClose">
    <div class="content">
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.id" label="产品编号" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.name" label="产品名称" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.barCode" label="产品条码" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.categoryId" label="产品分类编号" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.unitId" label="单位编号" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.status" label="产品状态" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.standard" label="产品规格" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.remark" label="产品备注" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.expiryDay" label="保质期天数" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.weight" label="基础重量（kg）" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.purchasePrice"
          label="采购价格，单位：元"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.salePrice"
          label="销售价格，单位：元"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.minPrice"
          label="最低价格，单位：元"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.warehouseLocationId" label="库位" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.warehouseAreaId" label="仓库区域" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.productAttribute" label="产品属性" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.unit" label="单位（基本单位）" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.warehousingRemark" label="入库备注" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.secondaryUnit" label="副单位" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.secondaryUnitQuantity"
          label="副单位数量"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.salePriceSecondary"
          label="销售单价（辅助单位）"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.costPriceSecondary"
          label="成本单价（辅助单位）"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.batchNumber" label="批号" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.supplierName" label="供应商名称" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.spec" label="规格" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.outerBoxSize" label="外箱尺寸" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.customerName" label="客户名称" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.itemNo" label="货号" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.packageInfo" label="包装" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.cuttingCostPerMeter"
          label="切割费用/米"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.piercingCostPerPiece"
          label="刺穿点费用/个"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox
          v-model="tempVisibleColumns.dottingCostPerPiece"
          label="打点费用/个"
          size="large"
        />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.weightNew" label="重量" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.size" label="尺码" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.singleWeight" label="单重" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.length" label="长" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.width" label="宽" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.height" label="高" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.density" label="密度" size="large" />
      </div>
      <div class="content-list">
        <el-checkbox v-model="tempVisibleColumns.contractNumber" label="合同编号" size="large" />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProductApi, ProductVO } from '@/api/erp/foundation/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { warehouseAreaApi } from '@/api/erp/foundation/warehouseArea'
import ProductForm from './components/ProductForm.vue'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
const statusOptions = ref<{ value: string; label: string }[]>([])
/** ERP 产品 列表 */
defineOptions({ name: 'Product' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const visibleColumns = ref({
  id: true, // 产品编号
  name: true, // 产品名称
  barCode: true, // 产品条码
  categoryId: true, // 产品分类编号
  unitId: true, // 单位编号
  status: true, // 产品状态
  standard: true, // 产品规格
  remark: true, // 产品备注
  expiryDay: true, // 保质期天数
  weight: true, // 基础重量（kg）
  purchasePrice: true, // 采购价格，单位：元
  salePrice: true, // 销售价格，单位：元
  minPrice: true, // 最低价格，单位：元
  warehouseLocationId: true, // 库位id
  warehouseAreaId: true, // 仓库区域id
  productAttribute: true, // 产品属性
  unit: true, // 单位（基本单位）
  warehousingRemark: true, // 入库备注
  secondaryUnit: true, // 副单位
  secondaryUnitQuantity: true, // 副单位数量
  salePriceSecondary: true, // 销售单价（辅助单位）
  costPriceSecondary: true, // 成本单价（辅助单位）
  batchtrue: true, // 批号
  supplierName: true, // 供应商名称
  spec: true, // 规格
  outerBoxSize: true, // 外箱尺寸
  customerName: true, // 客户名称
  itemNo: true, // 货号
  packageInfo: true, // 包装
  cuttingCostPerMeter: true, // 切割费用/米
  piercingCostPerPiece: true, // 刺穿点费用/个
  dottingCostPerPiece: true, // 打点费用/个
  weightNew: true, // 重量
  size: true, // 尺码
  singleWeight: true, // 单重
  length: true, // 长
  width: true, // 宽
  height: true, // 高
  density: true, // 密度
  contractNumber: true // 合同编号
})
const dialogVisible = ref(false)
const tempVisibleColumns = ref({ ...visibleColumns.value })
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  categoryId: undefined,
  status: undefined,
  standard: undefined,
  remark: undefined,
  expiryDay: undefined,
  weight: undefined,
  purchasePrice: undefined,
  createTime: [],
  productAttribute: undefined,
  batchNumber: undefined,
  supplierName: undefined,
  customerName: undefined,
  itemNo: undefined,
  size: undefined,
  singleWeight: undefined,
  contractNumber: undefined
})

// 列表字段确认选择
const handleConfirm = () => {
  visibleColumns.value = { ...tempVisibleColumns.value }
  dialogVisible.value = false

  // 这里可以添加保存到本地存储的逻辑
  // localStorage.setItem('visibleColumns', JSON.stringify(visibleColumns.value))
}
const btnLie = () => {
  tempVisibleColumns.value = { ...visibleColumns.value }
  dialogVisible.value = true
}

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productCategory = ref()
const warehouseArea = ref()
/** 查询列表 */
const getList = async () => {
  loading.value = true
    const data = {
    dictCode: 'status'
  }
  const response = await StockApi.getByDictCode(data)
  statusOptions.value = response.map((item) => ({
    value: item.id,
    label: item.description
  }))
  productCategory.value = await ProductCategoryApi.getProductCategoryList()
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProduct(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, 'ERP 产品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>